package utils

import (
	"crypto/md5"
	"encoding/hex"
	"time"

	"errors"

	"github.com/dgrijalva/jwt-go"
)

var secret = "rn13jUwFP2pYFzq2ORVD"

// CreateToken 生成token
func CreateToken(school_id int, institution_code string) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(24)).Unix()
	claims["iat"] = time.Now().Unix()
	claims["school_id"] = school_id
	claims["institution_code"] = institution_code
	token.Claims = claims
	return token.SignedString([]byte(secret))
}

// VerifyToken 校验token
func VerifyToken(input string, school_id int, institution_code string) (bool, error) {
	token, err := jwt.Parse(input, func(*jwt.Token) (interface{}, error) { return []byte(secret), nil })
	if err != nil {
		return false, err
	}
	if jwt.SigningMethodHS256.Alg() != token.Header["alg"] {
		return false, errors.New("加密方法不对称")
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		//log.Print(claims)
		if claims["school_id"].(float64) != float64(school_id) || claims["institution_code"].(string) != institution_code {
			return false, errors.New("token校验失败")
		}
	}
	return true, nil
}

func Md5(password string) string {
	h := md5.New()
	h.Write([]byte(password))
	return hex.EncodeToString(h.Sum(nil))
}
